<route lang="json5">
{
  style: {
    navigationBarTitleText: '村民入驻',
  },
}
</route>
<template>
  <view class="bg-#F6F6F6 overflow-auto w-100% h-100% box-border">
    <view class="w-100% position-relative">
      <view class="login_title pos-relative">
        <text class="z-100 pos-inherit mb-40rpx">请填写认证信息，提交后由管理员审批</text>
        <img
          class="w-100% h-100% pos-absolute top-0 left-0"
          src="../../static/images/loginBg1.png"
        />
      </view>
      <view class="mt--80rpx h-200rpx pb-40rpx bg-#fff flex flex-col justify-center items-center">
        <wd-img-cropper
          class="z-10"
          v-model="show"
          :img-src="src"
          @confirm="handleConfirmImg"
          @cancel="handleCancel"
        ></wd-img-cropper>
        <view class="profile flex-1">
          <view v-if="!imgSrc" @click="upload" class="w-150rpx h-150rpx pos-relative">
            <img class="w-100% h-100% z-10 pos-absolute" src="../../static/images/loginUser1.png" />
          </view>
          <wd-img
            v-if="imgSrc"
            round
            class="z-10"
            width="160rpx"
            height="160rpx"
            :src="imgSrc"
            mode="aspectFit"
            custom-class="profile-img"
            @click="upload"
          />
        </view>
        <view v-if="!imgSrc" style="font-size: 14px">点击上传头像</view>
      </view>
    </view>
    <!-- <view class="imgCont"></view> -->
    <view class="pb-20rpx">
      <wd-form ref="form" :model="model" class="pt-30rpx" :rules="rules">
        <wd-cell-group
          border
          style="border-bottom-right-radius: 36rpx; border-bottom-left-radius: 36rpx"
        >
          <wd-input
            label="姓名"
            label-width="100px"
            prop="residentName"
            placeholderClass="placeholderClass"
            placeholderStyle="{color:#bfbfbf}"
            v-model="model.residentName"
            placeholder="请输入本人姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
          />
          <wd-picker
            label="类型"
            placeholder="请选择居民类型"
            label-width="100px"
            prop="residentType"
            v-model="model.residentType"
            :columns="typelist"
            :rules="[{ required: true, message: '请选择居民类型' }]"
          />
          <wd-col-picker
            prop="address"
            label="选择户籍地"
            v-model="model.optionplace"
            :columns="area"
            label-width="100px"
            :column-change="columnChange"
            @confirm="handleConfirm"
            :rules="[{ required: true, message: '请选择户籍地' }]"
          ></wd-col-picker>

          <wd-input
            label="身份证号"
            label-width="100px"
            prop="idNumber"
            placeholder="请输入身份证号"
            clearable
            v-model="model.idNumber"
          />
        </wd-cell-group>
        <wd-cell-group border custom-class="group">
          <!-- <wd-calendar
            label="出生日期"
            label-width="100px"
            placeholder="请选择出生日期"
            prop="birthDate"
            v-model="model.birthDate"
          /> -->
          <wd-datetime-picker
            type="date"
            :minDate="minDate"
            :maxDate="maxDate"
            :default-value="maxDate"
            v-model="model.birthDate"
            placeholder="请选择出生日期"
            label="年月日"
            :rules="[{ required: true, message: '请选择出生日期' }]"
          />
          <wd-picker
            label="民族"
            placeholder="请选择民族"
            label-width="100px"
            prop="nation"
            v-model="model.nation"
            :columns="nationList"
            :rules="[{ required: true, message: '请选择民族' }]"
          />
          <wd-cell title="性别" prop="sex" label-width="100px">
            <wd-radio-group v-model="model.sex" inline shape="dot">
              <wd-radio value="1">男</wd-radio>
              <wd-radio value="2">女</wd-radio>
            </wd-radio-group>
          </wd-cell>
        </wd-cell-group>
        <wd-cell-group border custom-class="group">
          <wd-picker
            label="选择房屋"
            placeholder="请选择选择房屋"
            label-width="100px"
            prop="houseNumber"
            v-model="model.houseNumber"
            :columns="houseNumberList"
            :rules="[{ required: true, message: '请选择选择房屋' }]"
          />

          <wd-cell title="是否户主" prop="isHolder" label-width="100px">
            <wd-radio-group v-model="model.isHolder" inline shape="dot">
              <wd-radio value="1">是</wd-radio>
              <wd-radio value="0">否</wd-radio>
            </wd-radio-group>
          </wd-cell>
          <wd-picker
            label="与户主关系"
            placeholder="请选择与户主关系"
            label-width="100px"
            prop="relationship"
            v-model="model.relationship"
            :columns="optionrelation"
            :rules="[{ required: true, message: '请选择与户主关系' }]"
          />
          <wd-input
            label="个人年收入"
            label-width="100px"
            prop="income"
            clearable
            v-model="model.income"
            placeholder="请输入个人年收入"
          />
          <wd-input
            label="联系电话"
            label-width="100px"
            prop="telephone"
            clearable
            v-model="model.telephone"
            placeholder="请输入手机号码"
          />
          <wd-select-picker
            label="人员身份"
            label-width="100px"
            prop="residentLabel"
            v-model="model.residentLabel"
            :columns="classList"
            placeholder="请选择"
          />
        </wd-cell-group>
      </wd-form>
    </view>

    <view class="footer p-20rpx w-100% box-border">
      <wd-button plain block hairline @click="handleSubmit">提交审核</wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useColPickerData } from '@/hooks/useColPickerData'
import { getSimplePage, createResident } from '@/service/villager/index'
import { formatTime } from '@/utils/index'
import { useToast } from 'wot-design-uni'
import { useUserStore } from '@/store'
import { getClassify } from '@/service/index/index'
const userStore = useUserStore()
const { colPickerData, findChildrenByCode } = useColPickerData()
const src = ref<string>('')
const imgSrc = ref<string>('')
const show = ref<boolean>(false)
const toast = useToast()
const form = ref()
const minDate = new Date('1949-10-01 00:00:00').getTime()
const maxDate = Date.now()
const model = reactive<{
  residentName: string
  residentType: string
  address: string[]
  optionplace: string[]
  idNumber: string
  birthDate: string | number
  nation: string
  sex: number | null
  houseNumber: string
  relationship: string
  isHolder: string
  income: string
  telephone: string
  photo: string
  residentLabel: []
}>({
  residentName: '',
  residentType: '',
  optionplace: [],
  address: [],
  idNumber: '',
  birthDate: '',
  nation: '',
  sex: null,
  houseNumber: '',
  isHolder: '',
  relationship: '',
  income: '',
  telephone: '',
  residentLabel: [],
  photo: '',
})
const typelist = ref<any[]>([
  {
    value: '1',
    label: '本地居民',
  },
  {
    value: '2',
    label: '流动居民',
  },
])
const houseNumberList = ref<any[]>([
  {
    value: '1',
    label: '全部',
  },
])
const classList = ref<any[]>([
  {
    value: '1',
    label: '暂无数据',
  },
])
const optionrelation = [
  {
    value: 1,
    label: '配偶',
  },
  {
    value: 2,
    label: '子女',
  },
  {
    value: 3,
    label: '父母',
  },
  {
    value: 4,
    label: '兄弟',
  },
  {
    value: 5,
    label: '姊妹',
  },
  {
    value: 6,
    label: '祖父母',
  },
  {
    value: 7,
    label: '孙子女',
  },
  {
    value: 8,
    label: '儿媳',
  },
  {
    value: 9,
    label: '女婿',
  },
  {
    value: 10,
    label: '其他',
  },
  {
    value: 11,
    label: '户主',
  },
]
const nationList = [
  {
    value: 1,
    label: '汉族',
  },
  {
    value: 2,
    label: '壮族',
  },
  {
    value: 3,
    label: '回族',
  },
  {
    value: 4,
    label: '满族',
  },
  {
    value: 5,
    label: '维吾尔族',
  },
  {
    value: 6,
    label: '苗族',
  },
  {
    value: 7,
    label: '彝族',
  },
  {
    value: 8,
    label: '土家族',
  },
  {
    value: 9,
    label: '其他',
  },
]

/**
 * @description: form表单验证
 * @return {*}
 */
const rules: FormRules = {
  sex: [
    {
      required: true,
      message: '请输选择性别',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输选择性别'))
        }
      },
    },
  ],
  isHolder: [
    {
      required: true,
      message: '请输选择是否户主',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输选择是否户主'))
        }
      },
    },
  ],
  idNumber: [
    {
      required: true,
      message: '请输入正确的身份证号',
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\d|X|x]$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入身份证号'))
        }
      },
    },
  ],
  telephone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入手机号'))
        }
      },
    },
  ],
}
onLoad(() => {
  getInitData()
})
/**
 * @description: 头像上传
 * @return {*}
 */
function upload() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      src.value = tempFilePaths
      show.value = true
    },
  })
}
/**
 * @description: 选择图片
 * @param {*} event
 * @return {*}
 */
function handleConfirmImg(event) {
  const { tempFilePath } = event
  imgSrc.value = tempFilePath
  const uploadTask = uni.uploadFile({
    url: '/admin-api/infra/file/business/upload', // 自己文件上传的路径
    method: 'POST',
    filePath: tempFilePath,
    name: 'file',
    success: (res) => {
      const { data } = JSON.parse(res.data)
      model.photo = data.url
      console.log(data, 9999)
    },
    fail: (err) => {
      toast.error({
        msg: err + '',
      })
    },
    complete: () => {},
  })
}
function handleCancel(event) {
  console.log('取消', event)
}
/**
 * @description: 户籍数据
 * @return {*}
 */
const area = ref<any[]>([
  colPickerData.map((item) => {
    return {
      value: item.value,
      label: item.text,
    }
  }),
])
/**
 * @description: 户籍事件
 * @param {*} selectedItem
 * @param {*} resolve
 * @param {*} finish
 * @return {*}
 */
const columnChange = ({ selectedItem, resolve, finish }) => {
  const areaData = findChildrenByCode(colPickerData, selectedItem.value)
  if (areaData && areaData.length) {
    resolve(
      areaData.map((item) => {
        return {
          value: item.value,
          label: item.text,
        }
      }),
    )
  } else {
    console.log()
    finish()
  }
}
/**
 * @description: 户籍回显事件
 * @param {*} value
 * @param {*} selectedItems
 * @return {*}
 */
function handleConfirm({ value, selectedItems }) {
  model.address = selectedItems[0].label + selectedItems[1].label + selectedItems[2].label
}
/**
 * @description: 初始化数据
 * @return {*}
 */
async function getInitData() {
  const { data }: { data: any } = await getSimplePage()
  data.forEach((item) => {
    item.label = item.houseNumber
    item.value = item.houseNumber
  })
  houseNumberList.value = data
  const classData: any = await getClassify({
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_label',
  })

  classList.value = classData.data.list
}

/**
 * @description:表单提交
 * @return {*}
 */
function handleSubmit() {
  //
  form.value.validate().then(({ valid, errors }) => {
    if (valid) {
      createResident({
        ...model,
        residentLabel: model.residentLabel.join(','),
        birthDate: formatTime(model.birthDate, 'yyyy-MM-dd'),
        optionplace: undefined,
      }).then((res) => {
        if (res && res.code === 0) {
          toast.success({
            msg: '创建成功',
          })
          setTimeout(() => {
            userStore.setResidentId(res.data)
            uni.switchTab({ url: '/pages/index/index' })
            toast.close()
          }, 1000)
        } else {
          toast.error({
            msg: res.msg || '注册失败',
          })
          setTimeout(() => {
            userStore.setResidentId(res.data)
            uni.reLaunch({ url: '/pages/Login/index' })
            toast.close()
          }, 1000)
        }
      })
    }
  })
}
</script>
<style lang="scss" scoped>
.login_bg {
  position: absolute;
  width: 100%;
  height: 340rpx;
}
.login_title {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 270rpx;
  line-height: 250rpx;
  text-align: center;
}
.footer {
  bottom: 10rpx;
  width: 100%;
  background-color: #fff;
}
.imgCont {
  position: relative;
  z-index: 2;
  height: 130rpx;
  background: #fff;
  border-top-left-radius: 36rpx;
  border-top-right-radius: 36rpx;
}
:deep(.wd-button.is-medium.is-round) {
  width: 100%;
  color: #fff !important;
  background-color: #029669 !important;
}
.inline-txt {
  display: inline-block;
  margin: 0 8px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  vertical-align: middle;
}
:deep(.group) {
  margin-top: 12px;
  border-radius: 36rpx;
}
:deep(.wd-radio-group) {
  display: flex;
}
:deep(.wd-cell__left) {
  flex: 0.4 !important;
}
:deep(.wd-img-cropper) {
  z-index: 11 !important;
}
:deep(.wd-img) {
  left: 50%;
  z-index: 11;
  transform: translateX(-50%);
}
:deep(.wd-input__placeholder) {
  color: #bfbfbf !important;
}
:deep(.wd-input.is-disabled .wd-input__inner) {
  color: #262626 !important;
}
</style>
